package com.pms.repair.web;;
import com.google.common.base.Joiner;
import com.pms.exception.R;
import com.pms.partitionPoints.entity.KyEquipmentInfo;
import com.pms.partitionPoints.entity.KyGroupOrganization;
import com.pms.partitionPoints.entity.KyOrganization;
import com.pms.partitionPoints.entity.KyOrganizationEquipment;
import com.pms.partitionPoints.service.IKyEquipmentInfoService;
import com.pms.partitionPoints.service.IKyGroupOrganizationService;
import com.pms.partitionPoints.service.IKyOrganizationEquipmentService;
import com.pms.partitionPoints.service.IKyOrganizationService;
import com.pms.repair.entity.KyRepairMaintenance;
import com.pms.repair.service.IKyRepairMaintenanceService;
import com.pms.util.PhoneUtils;
import com.pms.util.idutil.SnowFlake;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.web.bind.annotation.*;
import com.pms.controller.BaseController;
import com.pms.repair.service.IKyRepairDeclareService;
import com.pms.repair.entity.KyRepairDeclare;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *设备保修申报表
 */
@RestController
@RequestMapping("/pip/kyRepairDeclare")
@Api(value="设备保修申报表",description = "设备保修申报表")
public class KyRepairDeclareController extends BaseController {
    @Autowired
    IKyRepairDeclareService kyRepairDeclareService;
    @Autowired
    IKyRepairMaintenanceService kyRepairMaintenanceService;
    @Autowired
    IKyOrganizationService kyOrganizationService;
    @Autowired
    IKyEquipmentInfoService kyEquipmentInfoService;
    @Autowired
    IKyOrganizationEquipmentService kyOrganizationEquipmentService;
    @Autowired
    IKyGroupOrganizationService groupOrganizationService;

    /**
     * 添加申报测点维修
     * @param equipmentInfoId
     * @param declareType
     * @param declarePerson
     * @param declarePhone
     * @param description
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加申报测点维修")
    @ApiImplicitParams({
            @ApiImplicitParam(name="roleId",value="角色ID",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="equipmentInfoId",value="设备ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="declareType",value="1.未知2.设备故障3.环境因素",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="declarePerson",value="申报人",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="declarePhone",value="申报人电话",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="description",value="故障描述",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="companyCode",value="公司编码",required = true,dataType = "String",paramType="form"),
    })
    public R add(Long roleId,Long equipmentInfoId,Integer declareType,String declarePerson, String declarePhone,String description,String companyCode){
        parameterIsNull(equipmentInfoId,"请填写设备ID");
        parameterIsNull(roleId,"请填写角色ID");
        parameterIsNull(declareType,"请填写故障类型");
        parameterIsNull(declarePerson,"请填写申报人");
        parameterIsNull(declarePhone,"请填写申报人电话");
        parameterIsNull(description,"请填写故障描述");
        parameterIsNull(companyCode,"请填写公司编码");
        Boolean is=PhoneUtils.isPhone(declarePhone);
        if(is==false){return  R.error(400,"申报人电话格式错误");}
        KyRepairDeclare declare=kyRepairDeclareService.selectOne(new EntityWrapper<KyRepairDeclare>().eq("equipment_info_id",equipmentInfoId).and().eq("state_",1));
        if (declare!=null){return  R.error(400,"该测点已申报,请查看");}
        KyRepairDeclare entity=new KyRepairDeclare();
        KyEquipmentInfo eq=kyEquipmentInfoService.selectById(equipmentInfoId);
        if (eq==null){return  R.error(400,"测点信息不存在");}
        entity.setEquipmentInfoName(eq.getName());
        entity.setTarget(2);
        entity.setRoleId(roleId);
        entity.setCompanyCode(companyCode);//公司编码
        entity.setDeclareType(declareType);//故障类型
        entity.setDeclarePerson(declarePerson);//申报人
        entity.setDeclarePhone(declarePhone);//申报人电话
        entity.setDescription(description);//故障描述
        entity.setEquipmentInfoId(equipmentInfoId);//设备ID
        entity.setDeclareData(new Date());//申报时间
        entity.setState(1);//状态1待处理2拒绝受理3已受理
        entity.setCrtTime(new Date());//创建时间
        entity.setIsRead(2);
        kyRepairDeclareService.insert(entity);
        return R.ok();
    }

    /**
     * 查询单条申报测点维修信息
     * @param repairDeclareId
     * @return
     */
    @ApiOperation(value = "查询单条申报测点维修信息")
    @GetMapping(value = "/findById")
    @ApiImplicitParams({
            @ApiImplicitParam(name="repairDeclareId",value="申报测点维修ID",required = true,dataType = "Long",paramType="form"),
    })
    public R findById(@RequestParam Long repairDeclareId){
        parameterIsNull(repairDeclareId,"设备保修申报ID不能为空");
        KyRepairDeclare repair= kyRepairDeclareService.selectById(repairDeclareId);
        return R.ok().put("data",repair);
    }

    /**
     * 添加受理申报信息
     * @param acceptPerson
     * @param acceptPhone
     * @return
     */
    @ApiOperation(value = "添加受理申报信息")
    @PostMapping("/addAcceptPerson")
    @ApiImplicitParams({
            @ApiImplicitParam(name="repairDeclareId",value="申报测点维修ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="acceptPerson",value="受理人",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="acceptPhone",value="受理人电话",required = true,dataType = "String",paramType="form"),
    })
    public R addAcceptPerson(String repairDeclareId,String acceptPerson,String acceptPhone){
        parameterIsNull(repairDeclareId,"设备保修申报ID不能为空");
        parameterIsNull(acceptPerson,"受理人不能为空");
        parameterIsNull(acceptPhone,"受理人电话不能为空");
        Boolean is=PhoneUtils.isPhone(acceptPhone);
        if(is==false){return  R.error(400,"受理人电话格式错误");}
        KyRepairDeclare repair=kyRepairDeclareService.selectById(repairDeclareId);
        if (repair==null){return  R.error(400,"设备保修申报信息不存在");}
        if (repair.getState()==3){
            return  R.error(400,"该条申报信息已受理,请修改");
        }
        repair.setAcceptPerson(acceptPerson);//受理人
        repair.setAcceptPhone(acceptPhone);//受理电话
        repair.setAcceptData(new Date());//受理时间
        repair.setState(3);//修改状态为已受理
        repair.setIsRead(2);//是否已读(1已读2未读)
        repair.setCrtUser(getCurrentUserMap().get("userName"));//受理管理员
        KyRepairMaintenance entity=new KyRepairMaintenance();
        entity.setRepairMaintenanceId(new SnowFlake(0,0).nextId());
        entity.setEquipmentInfoId(repair.getEquipmentInfoId());//设备ID
        entity.setEquipmentInfoName(repair.getEquipmentInfoName());//设备名称
        entity.setRepairDeclareId(repair.getRepairDeclareId());//设备申报ID
        entity.setState(3);//待处理
        kyRepairMaintenanceService.insert(entity);
        kyRepairDeclareService.updateById(repair);
        return R.ok();
    }

    /**
     * 修改受理申报信息
     * @param acceptPerson
     * @param acceptPhone
     * @return
     */
    @ApiOperation(value = "修改受理申报信息")
    @PostMapping("/updateAcceptPerson")
    @ApiImplicitParams({
            @ApiImplicitParam(name="repairDeclareId",value="申报测点维修ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="acceptPerson",value="受理人",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="acceptPhone",value="受理人电话",required = true,dataType = "String",paramType="form"),
    })
    public R updateAcceptPerson(String repairDeclareId,String acceptPerson,String acceptPhone){
        parameterIsNull(repairDeclareId,"请填写设备保修申报ID");
        parameterIsNull(acceptPerson,"受理人不能为空");
        parameterIsNull(acceptPhone,"受理人电话不能为空");
        Boolean is=PhoneUtils.isPhone(acceptPhone);
        if(is==false){return  R.error(400,"受理人电话格式错误");}
        KyRepairDeclare repair=kyRepairDeclareService.selectById(repairDeclareId);
        if (repair==null){return  R.error(400,"设备保修申报信息不存在");}
        repair.setAcceptPerson(acceptPerson);//受理人
        repair.setAcceptPhone(acceptPhone);//受理电话
        repair.setAcceptData(new Date());//受理时间
        repair.setState(3);//修改状态为已受理
        repair.setIsRead(2);//是否已读(1已读2未读)
        kyRepairDeclareService.updateById(repair);
        return R.ok();
    }

    /**
     * 修改状态为拒绝受理
     * @param repairDeclareId
     * @return
     */
    @ApiOperation(value = "修改状态为拒绝受理")
    @PostMapping("/updateState_2")
    @ApiImplicitParams({
            @ApiImplicitParam(name="repairDeclareId",value="申报测点维修ID",required = true,dataType = "Long",paramType="form")
    })
    public R updateState_2(String repairDeclareId){
        parameterIsNull(repairDeclareId,"请填写设备保修申报ID");
        KyRepairDeclare repair=kyRepairDeclareService.selectById(repairDeclareId);
        if (repair==null){return  R.error(400,"设备保修申报信息不存在");}
        repair.setState(2);//修改状态为拒绝受理
        repair.setIsRead(2);//是否已读(1已读2未读)
        repair.setUpdUser(getCurrentUserMap().get("userName"));
        repair.setUpdTime(new Date());
        kyRepairDeclareService.updateById(repair);
        return R.ok();
    }
    /**
     * 维修信息修改
     * @param repairMaintenanceId
     * @param startData
     * @param endData
     * @param state
     * @param maintenanceCosts
     * @param maintenanceDescription
     * @return
     */
    @ApiOperation(value = "维修信息修改")
    @PostMapping("/update/Maintenance")
    @ApiImplicitParams({
            @ApiImplicitParam(name="repairMaintenanceId",value="设备维修信息ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="startData",value="开始时间",required = false,dataType = "Date",paramType="form"),
            @ApiImplicitParam(name="endData",value="结束时间",required = false,dataType = "Date",paramType="form"),
            @ApiImplicitParam(name="state",value="维修状态1.维修成功2维修失败3.待处理",required = false,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="maintenanceCosts",value="维修费用",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="maintenanceDescription",value="维修描述",required = false,dataType = "String",paramType="form"),
    })
    public R updateMaintenance(Long repairMaintenanceId,String startData, String endData, Integer state, String maintenanceCosts, String maintenanceDescription){
        parameterIsNull(repairMaintenanceId,"请填写设备申报信息ID");
        KyRepairMaintenance maintenance=kyRepairMaintenanceService.selectById(repairMaintenanceId);
        if (maintenance==null){ return  R.error(400,"该测点维修信息不存在");}
        KyRepairDeclare repair=kyRepairDeclareService.selectById(maintenance.getRepairDeclareId());
        if (repair==null){return  R.error(400,"设备保修申报信息不存在");}
        if (repair.getState()!=3){return  R.error(400,"设备申报信息还未受理，请稍等！");}
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.isNotBlank(startData)){
            Date start = null;
            try {
                start = sdf.parse(startData);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            maintenance.setStartData(start);//开始时间
        }
        if (StringUtils.isNotBlank(endData)){
            Date end = null;
            try {
                end = sdf.parse(endData);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            maintenance.setEndData(end);//结束时间
        }
        if (null!=state){
            maintenance.setState(state);//维修状态：1维修成功2维修失败
        }
        if (StringUtils.isNotBlank(maintenanceCosts)){
            BigDecimal bd=new BigDecimal(maintenanceCosts);
            maintenance.setMaintenanceCosts(bd);//维修费用
        }
        if (StringUtils.isNotBlank(maintenanceDescription)){
            maintenance.setMaintenanceDescription(maintenanceDescription);//维修描述
        }
        repair.setTarget(1);
        repair.setIsRead(2);//是否已读(1已读2未读)
        kyRepairDeclareService.updateById(repair);
        kyRepairMaintenanceService.updateById(maintenance);
        return R.ok();
    }


    /**
     * 查询单条设备维修信息
     * @param repairMaintenanceId
     * @return
     */
    @ApiOperation(value = "查询单条设备维修信息")
    @GetMapping(value = "/seteleByMaintenance")
    @ApiImplicitParams({
            @ApiImplicitParam(name="repairMaintenanceId",value="设备维修信息ID",required = true,dataType = "Long",paramType="form"),
    })
    public R seteleByMaintenance(@RequestParam Long repairMaintenanceId){
        parameterIsNull(repairMaintenanceId,"设备保修申报ID不能为空");
        KyRepairMaintenance Maintenance= kyRepairMaintenanceService.seteleByMaintenance(repairMaintenanceId);
        return R.ok().put("data",Maintenance);
    }

    /**
     * 分页查询申报维修信息
     * @param limit
     * @param page
     * @param id
     * @return
     */
    @ApiOperation(value = "分页查询申报信息")
    @GetMapping("/declarePage")
    @ApiImplicitParams({
            @ApiImplicitParam(name="limit",value="分页条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="page",value="分页页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="id",value="分区ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="name",value="查询字段",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="target",value="标识查询层级（1查询测点2查询分区3查询系统）",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="companyCode",value="公司编码",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="maintenanceName",value="查询字段(维修信息查询)",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="repairLimit",value="分页条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="repairPage",value="分页页数",required = false,dataType = "int",paramType="form"),
    })
    public R declarePage(int limit,int page,Long id,String name,int target,String companyCode,String maintenanceName,int repairLimit,int repairPage){
        parameterIsNull(id,"请填写分区ID");
        parameterIsNull(target,"标识是否是测点");
        parameterIsNull(companyCode,"请填写公司编码");
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        if (repairLimit<1){repairLimit=10;}
        if (repairPage<1){repairPage=1;}
        Map<String,Object>  map=new HashMap<>();
        List<String> str=new ArrayList<>();
        Map<String,Object>  paraMap=new HashMap<>();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("target",target);
        Page<KyRepairDeclare> pageList = new Page<>(page,limit);
        Page<KyRepairMaintenance> pageSize = new Page<>(repairPage,repairLimit);
        if (target==1){
            parameter.put("target",1);
            parameter.put("equipment_info_id",id);
            KyEquipmentInfo eqinfo =kyEquipmentInfoService.selectOne(new EntityWrapper<KyEquipmentInfo>().eq("id",id));
            if (eqinfo!=null&&eqinfo.getStatus()==1){
                paraMap.put("ids",id);
            }else {
                paraMap.put("ids",-1);
            }
        }else if (target==2){
            //查询当前分区ID的所有下级分区
            List<String> str2 = kyOrganizationService.getOrgIdsByCurrentId(Integer.parseInt(id.toString()));
            String organizationIdList = Joiner.on(",").join(str2);
            if (!StringUtils.isNotBlank(organizationIdList)){
                organizationIdList=null;
            } //查询所有下级分区的分区计量测点ID
            List<Integer> strw = kyOrganizationEquipmentService.getEquipmentsByOrganizationList(organizationIdList);
            String organizationId = Joiner.on(",").join(strw);
            if(!StringUtils.isNotBlank(organizationId)){
                map.put("pageList",pageList);
                map.put("pageSize",pageSize);
                return R.ok().put("data",map);
            }else{
                paraMap.put("ids",organizationIdList);
                parameter.put("organizationId",organizationId);
            }
            parameter.put("target",2);
        }else if (target==3){
            // 获取当前用户角色
            Map<String,String> currentUserMap=getCurrentUserMap();
            String  roleType= currentUserMap.get("roleType");
            parameterIsNull(roleType,"请先登录");
            parameter.put("roleType",roleType);
            if (roleType.equals("1")){//系统默认
                parameter.put("company_code",companyCode);
                parameter.put("target",3);
                List<KyRepairDeclare>  list=kyRepairDeclareService.selectByListRepairDeclare(companyCode);
                if (list.size()>0){
                    for (int x=0;x<list.size();x++){
                        str.add(list.get(x).getEquipmentInfoId().toString());
                    }
                    String ids= Joiner.on(",").join(str);
                    paraMap.put("ids",ids);
                }else {
                    paraMap.put("ids",-1);
                }
            }else if (roleType.equals("2")){//自定义角色
                List<String> st=new ArrayList<>();
                //查询当前用户所拥有的分区树权限
                List<KyGroupOrganization> groupOrganization=groupOrganizationService.selectList(new EntityWrapper<KyGroupOrganization>().eq("group_id",currentUserMap.get("roleId")));
                if (groupOrganization!=null||groupOrganization.size()>0){
                    for (int x=0;x<groupOrganization.size();x++){
                        KyOrganization organization= kyOrganizationService.selectById(groupOrganization.get(x).getOrganizationId());
                          if (null==organization){
                              continue;
                          }
                       if (organization.getOrganizationgradeid()==1){//为顶级的时候移除顶级ID
                           groupOrganization.remove(groupOrganization.get(x));
                       }
                        //分区树查询计量分区测点
                        List<KyOrganizationEquipment>  ord=kyOrganizationEquipmentService.selectList(new EntityWrapper<KyOrganizationEquipment>().eq("organizationId",groupOrganization.get(x).getOrganizationId()));
                        if (ord==null||ord.size()<0){continue;}
                        for (int y=0;y<ord.size();y++){
                            st.add(ord.get(y).getEquipmentid().toString());
                        }
                    }
                    String ids=String.join(",",st);
                    parameter.put("ids",ids);
                    paraMap.put("ids",ids);
                }
            }
        }
        if (StringUtils.isNotBlank(name)) {
            parameter.put("name", "and (re.equipment_info_name like '%"+name+"%' or re.declare_person like '%"+name+"%'" +
                    "or re.declare_phone like '%"+name+"%'or re.accept_person like '%"+name+"%'or re.crt_user like '%"+name+"%'" +
                    "or re.accept_phone like '%"+name+"%' or re.description like '%"+name+"%' or re.company_code like '%"+name+"%')");
        }
        if (StringUtils.isNotBlank(maintenanceName)) {
            paraMap.put("name", "and (equipment_info_name like '%"+maintenanceName+"%'" +
                    "or maintenance_description like '%"+maintenanceName+"%')");
        }
        parameter.put("page",(page-1) * limit);
        parameter.put("limit",limit);

        paraMap.put("limit",repairLimit);
        paraMap.put("page",(repairPage-1)*repairLimit);
        pageList = kyRepairDeclareService.selectByPageRepairDeclare(pageList,parameter);
        pageSize = kyRepairMaintenanceService.selectByPageMap(pageSize,paraMap);
        map.put("pageList",pageList);
        map.put("pageSize",pageSize);
        return R.ok().put("data",map);
    }

    /**
     * 分页查询维修信息
     * @param limit
     * @param page
     * @param repairDeclareId
     * @param name
     * @return
     */
    @ApiOperation(value = "分页维修信息")
    @GetMapping("/maintenancePage")
    @ApiImplicitParams({
            @ApiImplicitParam(name="limit",value="分页条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="page",value="分页页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="repairDeclareId",value="申报信息ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="name",value="查询字段",required = false,dataType = "String",paramType="form"),
    })
    public R maintenancePage(int limit,int page,Long repairDeclareId,String name){
        parameterIsNull(repairDeclareId,"请填写设备申报信息ID");
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("repairDeclareId",repairDeclareId);
        Page<KyRepairMaintenance> pageList = new Page<KyRepairMaintenance>(page,limit);
        if (StringUtils.isNotBlank(name)) {
            parameter.put("name", "and (equipment_info_name like '%"+name+"%' or maintenance_costs like '%"+name+"%'" +
                    "or maintenance_description like '%"+name+"%')");
        }
        parameter.put("limit",limit);
        parameter.put("page",(page-1)*limit);
        pageList = kyRepairMaintenanceService.selectByPageList(pageList,parameter);
        return R.ok().put("data",pageList);
    }
}





